package com.colter.project.sample.thread.part03.test1;

import java.util.concurrent.Semaphore;

//信号量（Semaphore）
public class Test1 {
	public static void main(String[] args) {
		PrintQueue printQueue = new PrintQueue();
		Thread[] threads = new Thread[10];
		for (int i = 0; i < threads.length; i++) {
			threads[i] = new Thread(new Job(printQueue),"Thread "+i);
		}
		
		for (int i = 0; i < threads.length; i++) {
			threads[i].start();
		}
	}
}

class PrintQueue {
	private final Semaphore semaphore;

	public PrintQueue() {
		semaphore = new Semaphore(1);
	}

	public void printJob() {
		try {
			semaphore.acquire();
			long duration = (long) (Math.random() * 10);
			System.out.println("print job during " + duration + " seconds. name:" + Thread.currentThread().getName());
			Thread.sleep(duration * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			semaphore.release();
		}
	}
}


class Job implements Runnable{
	private PrintQueue printQueue;

	public Job(PrintQueue printQueue) {
		super();
		this.printQueue = printQueue;
	}

	@Override
	public void run() {
		System.out.println("start print. name:" + Thread.currentThread().getName());
		printQueue.printJob();
		System.out.println("end print. name:" + Thread.currentThread().getName());
	}
	
	
	
}